package Controller;

import Model.Result;
import Model.ResultBean;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.sql.DataSource;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

@WebServlet("/ReleaseScore")
public class ReleaseScore extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Context context = null;
        String sno = request.getParameter("sno");
        HttpSession session = request.getSession();
        try {
            context = new InitialContext();
            Context contextNeeded = (Context) context.lookup("java:comp/env");
            DataSource ds = (DataSource) contextNeeded.lookup("wq");// 获得连接池。
            Connection conn = null;
            ResultSet rs;
            String sql;
            PreparedStatement pstmt;
            conn = ds.getConnection();//获得数据源
            sql = "select score.id,user.name,score.sno,sport.sname,dept,class,srank,grade from score natural join user natural join sport where score.sno=?";
            pstmt =  conn.prepareStatement(sql);
            pstmt.setString(1,sno);
            rs = pstmt.executeQuery();
            ResultBean sb = (ResultBean) session.getAttribute("resultBean");
            if(sb==null){
                sb = new ResultBean();
            }
            ResultBean temp = new ResultBean();
            Result d;
            while (rs.next()){
                d = new Result();
                d.setId(rs.getString(1));
                d.setName(rs.getString(2));
                d.setSno(rs.getString(3));
                d.setSname(rs.getString(4));
                d.setDept(rs.getString(5));
                d.setSporter_class(rs.getString(6));
                d.setRank(rs.getInt(7));
                d.setGrade(rs.getString(8));
                temp.add(d);
            }
            sb.setResults(temp.getResults());
            session.setAttribute("resultBean",sb);
            conn.close();
            response.sendRedirect("admin/release_score2.jsp");
        } catch (NamingException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            System.out.println("加载不成功");
        }
    }
}
